<?php
defined( 'BASEPATH' ) or exit( 'No direct script access allowed' );
class Content_model extends MY_Model
{
    function get_list_count($keywords, $cid)
    {
        $this->_db->select( $this->_table, 'count(*)' );
        $where = '';
        $data = array ();
        if (! empty( $keywords ))
        {
            $where .= '`title` like ? and ';
            $data[] = "%$keywords%";
        }
        if (is_array( $cid ))
        {
            
            $where .= '`cid` in(?) and `deleted`=0';
            $data = array_merge( $data, $cid );
        }
        else
        {
            $where .= '`cid`=? and `deleted`=0';
            $data[] = $cid;
        }
        $this->_db->where( $where, $data );
        return ( int ) $this->_db->fetch_cell();
    }
    function get_list($keywords, $cid, $length = 10, $begin = 0, $desc = false)
    {
        $this->_db->select( $this->_table, '`id`,`cid`,`flag`,`img_cover`,`uri`,`title`,`subtitle`,`summary`,`price`,`price_old`,`file_type`,`file_size`,`properties`,`clicked`,`sort`,`add_time`,`enable`' );
        
        $where = '';
        $data = array ();
        if (! empty( $keywords ))
        {
            $where .= '`title` like ? and ';
            $data[] = "%$keywords%";
        }
        if (is_array( $cid ))
        {
            
            $where .= '`cid` in(?) and `deleted`=0';
            $data = array_merge( $data, $cid );
        }
        else
        {
            $where .= '`cid`=? and `deleted`=0';
            $data[] = $cid;
        }
        $this->_db->where( $where, $data );
        if ($desc)
        {
            $this->_db->order( '`sort` desc,`id` desc' );
        }
        else
        {
            $this->_db->order( '`sort` desc,`id`' );
        }
        $this->_db->limit( $length, $begin );
        return $this->_db->fetch_all();
    }
    function get($id)
    {
        $this->_db->select( $this->_table );
        $this->_db->where( '`id`=? and `deleted`=0', $id );
        $this->_db->limit( 1 );
        return $this->_db->fetch_row();
    }
    function max_sort($gid)
    {
        $this->_db->select( $this->_table, 'max(`sort`)' );
        $this->_db->where( '`gid`=? and `deleted`=0', $gid );
        return ( int ) $this->_db->fetch_cell();
    }
    // 多组一次取出
    function get_article($cids)
    {
        $result = array ();
        if (empty( $cids ))
        {
            return $result;
        }
        $this->_db->select( $this->_table, '`id`,`cid`,`uri`,`title`,`subtitle`,`enable`' );
        $this->_db->where( 'cid in(?) and `deleted`=0', $cids );
        $this->_db->order( '`cid`,`sort` desc,`id` desc' );
        $articles = $this->_db->fetch_all();
        foreach ( $articles as &$item )
        {
            $result[$item['cid']][] = &$item;
        }
        return $result;
    }
}